import { join } from 'node:path'
import AutoLoad, { AutoloadPluginOptions } from '@fastify/autoload'
import { FastifyPluginAsync, FastifyServerOptions } from 'fastify'
import swagger from '@fastify/swagger'
import swaggerUi from '@fastify/swagger-ui'
import cors from '@fastify/cors'
import { config } from './config'

export interface AppOptions extends FastifyServerOptions, Partial<AutoloadPluginOptions> {}
// Pass --options via CLI arguments in command to enable these options.
const options: AppOptions = {}

const app: FastifyPluginAsync<AppOptions> = async (fastify, opts): Promise<void> => {
    // Place here your custom code!

    // 注册 CORS 支持
    await fastify.register(cors, {
        origin: config.cors.origin.split(','),
        credentials: config.cors.credentials
    })

    // 注册 Swagger（OpenAPI 文档生成器）
    await fastify.register(swagger, {
        openapi: {
            openapi: '3.0.0',
            info: {
                title: 'Check-in Backend API',
                description: '签到系统后端 API 文档 - 提供完整的考勤、事件管理、成员管理等功能',
                version: '1.0.0',
                contact: {
                    name: 'API Support',
                    email: 'support@checkin.example.com'
                },
                license: {
                    name: 'MIT',
                    url: 'https://opensource.org/licenses/MIT'
                }
            },
            servers: [
                {
                    url: 'http://localhost:3000',
                    description: '开发环境'
                },
                {
                    url: 'https://api.checkin.example.com',
                    description: '生产环境'
                }
            ],
            tags: [
                { name: '认证', description: '用户登录、Token 管理' },
                { name: '签到', description: '签到、签退、考勤管理' },
                { name: '事件', description: '事件的创建、管理、查询' },
                { name: '签到码', description: '签到码生成和验证' },
                { name: '成员', description: '成员管理、导入导出' },
                { name: '组织', description: '组织和群组管理' }
            ],
            components: {
                securitySchemes: {
                    bearerAuth: {
                        type: 'http',
                        scheme: 'bearer',
                        bearerFormat: 'JWT',
                        description: '使用 JWT Token 进行认证。格式: Bearer <token>'
                    }
                }
            },
            security: []
        }
    })

    // 注册 Swagger UI（可视化界面）
    await fastify.register(swaggerUi, {
        routePrefix: '/docs',
        uiConfig: {
            docExpansion: 'list',
            deepLinking: true,
            displayOperationId: false,
            displayRequestDuration: true,
            filter: true,
            showExtensions: false,
            showCommonExtensions: false,
            tryItOutEnabled: true
        },
        uiHooks: {
            onRequest: function (request, reply, next) {
                next()
            },
            preHandler: function (request, reply, next) {
                next()
            }
        },
        staticCSP: true,
        transformStaticCSP: header => header,
        transformSpecification: (swaggerObject, request, reply) => {
            return swaggerObject
        },
        transformSpecificationClone: true
    })

    // Do not touch the following lines

    // This loads all plugins defined in plugins
    // those should be support plugins that are reused
    // through your application
    // eslint-disable-next-line no-void
    void fastify.register(AutoLoad, {
        dir: join(__dirname, 'plugins'),
        options: opts
    })

    // This loads all plugins defined in routes
    // define your routes in one of these
    // eslint-disable-next-line no-void
    void fastify.register(AutoLoad, {
        dir: join(__dirname, 'routes'),
        options: opts
    })
}

export default app
export { app, options }
